package com.raycloud.action.user;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.raycloud.action.common.BaseAction;
import com.raycloud.common.Constants;
import com.raycloud.common.ScopeConstants;
import com.raycloud.domain.Msg;
import com.raycloud.domain.User;
import com.raycloud.manager.MsgMgr;

public class FetchMsgAction extends BaseAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(FetchMsgAction.class);
	
	private MsgMgr msgMgr;
	
	private String pageNo;

	public String execute() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		try {
			User user = (User) session.get(ScopeConstants.USER);
			
			int pageNoI = getPageNoInteger();
			int firstResult = (pageNoI - 1) * Constants.MSG_FETCH_SIZE;
			int maxResults = Constants.MSG_FETCH_SIZE;
			
			List<Msg> msgs = msgMgr.queryUserMsgs(user, firstResult, maxResults);
			if(msgs == null) {
				msgs = new ArrayList<Msg>();
			}
			JSONObject responseJson = new JSONObject();
			responseJson.put("success", "true");
			responseJson.put("body", msgs);
			
			out.println(responseJson.toString());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			JSONObject responseJson = new JSONObject();
			responseJson.put("success", "true");
			responseJson.put("msg", "读取微博失败");
			out.println(responseJson.toString());
		} finally {
			if(out != null) {
				out.close();
			}
		}
		
		return null;
	}
	
	private int getPageNoInteger() {
		try {
			return Integer.valueOf(pageNo);
		} catch (Exception e) {
			return 1;
		}
	}

	public void setPageNo(String pageNo) {
		this.pageNo = pageNo;
	}

	public void setMsgMgr(MsgMgr msgMgr) {
		this.msgMgr = msgMgr;
	}

	
}
